#pragma once
#include "log.hpp"
#include "Protocol.hpp"
#include <string>
#include <cstring>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cerrno>
#include <cstdlib>
#include <arpa/inet.h>
#include <netinet/in.h>

#define NUM 1024

namespace Client
{
    class tcpClient
    {
    public:
        tcpClient(const std::string &serverip, const uint16_t &serverport)
            : _serverip(serverip), _serverport(serverport), _sock(-1)
        {
        }

        void initClient()
        {
            // 1.创建socket
            _sock = socket(AF_INET, SOCK_STREAM, 0);
            if (_sock < 0)
            {
                std::cerr << "socket error: " << errno << " : " << strerror(errno) << std::endl;
                exit(2);
            }
            // 2.client要不要bind[必须要的]，client要不要显示的bind，不需要
            // 3.客户端不需要listen
            // 4.也不需要accept
        }

        void start()
        {
            // 5.要发起链接
            struct sockaddr_in server;
            memset(&server, 0, sizeof server);
            server.sin_family = AF_INET;
            server.sin_port = htons(_serverport);
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());

            if (connect(_sock, (struct sockaddr *)&server, sizeof server) != 0)
            {
                std::cerr << "connect error: " << errno << " : " << strerror(errno) << std::endl;
            }
            else
            {
                std::string msg;
                std::string inbuffer;
                while (true)
                {
                    std::cout << "mycal>>> ";
                    std::getline(std::cin, msg);

                    Request req(10, 10, '+');
                    std::string content;
                    req.serialize(&content);
                    std::string send_string = enLength(content);
                    send(_sock, send_string.c_str(), send_string.size(), 0);

                    std::string package, text;
                    if (!recvPackage(_sock, inbuffer, &package))
                        continue;
                    if (!deLength(package, &text))
                        continue;
                    Response resp;
                    resp.deserialize(text);
                    std::cout << "exitcode: " << resp.exitcode << std::endl;
                    std::cout << "result: " << resp.result << std::endl;
                }
            }
        }

        ~tcpClient()
        {
            if (_sock >= 0)
                close(_sock);
        }

    private:
        int _sock;
        std::string _serverip;
        uint16_t _serverport;
    };
}